package jjn.carl.greedy;

import java.util.*;

/**
 * @author Jjn
 * @since 2023/8/2 14:40
 */
public class LeetCode56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(i -> i[0]));
        Deque<int[]> result = new LinkedList<>();
        for (int i = 0; i < intervals.length; i++) {
            int left = intervals[i][0], right = intervals[i][1];
            if (result.isEmpty() || result.peekLast()[1] < left) {
                result.offer(new int[]{left, right});
                continue;
            }
            result.peekLast()[1] = Math.max(result.peekLast()[1], right);
        }
        return result.toArray(new int[result.size()][]);
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int total = scanner.nextInt();
            int[][] intervals = new int[total][2];
            for (int i = 0; i < total; i++) {
                for (int j = 0; j < 2; j++) {
                    intervals[i][j] = scanner.nextInt();
                }
            }
            int[][] merge = new LeetCode56().merge(intervals);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("[");
            for (int[] ints : merge) {
                stringBuilder.append(Arrays.toString(ints));
                stringBuilder.append(",");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            stringBuilder.append("]");
            System.out.println(stringBuilder);
        }
    }
}
